<template>
  <div class="status-log-container">
    <!-- 双列布局上部分 -->
    <div class="top-section">
      <!-- 左侧流程图 -->
      <div class="flow-section">
        <!-- <h3>动态流程
          <span v-if="itemData">
            --- {{ itemData.spec.desc.docs }}
          </span>
        </h3> -->
        <div class="flow-diagram">
          <FlowDiagramNew :item-data="itemData" :is-galaxea="isGalaxea" />
        </div>
      </div>

      <!-- 右侧相机监控 -->
      <div class="camera-section">
        <h3>相机监控</h3>
        <div class="camera-views">
          <div class="camera-view">
            <div class="camera-header">
              <span>相机 1 - 监控画面</span>
              <div class="camera-controls">
                <button @click="controlCamera('camera1', 'play')" v-if="!cameraStatus.camera1.playing">播放</button>
                <button @click="controlCamera('camera1', 'stop')" v-if="cameraStatus.camera1.playing">停止</button>
                <span v-if="cameraStatus.camera1.error" class="camera-error">连接失败</span>
              </div>
            </div>
            <div class="camera-content">
              <video ref="camera1Video" class="camera-video" controls muted></video>
              <div v-if="!cameraStatus.camera1.playing && !cameraStatus.camera1.error" class="camera-placeholder">
                点击播放按钮查看监控画面
              </div>
              <div v-if="cameraStatus.camera1.loading" class="camera-loading">
                <div class="loading-spinner"></div>
                <div>加载中...</div>
              </div>
            </div>
          </div>
          <div class="camera-view">
            <div class="camera-header">
              <span>相机 2 - 监控画面</span>
              <div class="camera-controls">
                <button @click="controlCamera('camera2', 'play')" v-if="!cameraStatus.camera2.playing">播放</button>
                <button @click="controlCamera('camera2', 'stop')" v-if="cameraStatus.camera2.playing">停止</button>
                <span v-if="cameraStatus.camera2.error" class="camera-error">连接失败</span>
              </div>
            </div>
            <div class="camera-content">
              <video ref="camera2Video" class="camera-video" controls muted></video>
              <div v-if="!cameraStatus.camera2.playing && !cameraStatus.camera2.error" class="camera-placeholder">
                点击播放按钮查看监控画面
              </div>
              <div v-if="cameraStatus.camera2.loading" class="camera-loading">
                <div class="loading-spinner"></div>
                <div>加载中...</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 状态日志表格 -->
    <div class="status-table-section">
      <h3>状态日志</h3>
      <div class="table-container">
        <!-- 加载中状态 -->
        <div v-if="eventsLoading" class="loading-container">
          <div class="loading-spinner"></div>
          <div class="loading-text">正在获取事件数据...</div>
        </div>

        <!-- 无数据状态 -->
        <div v-else-if="events.length === 0" class="empty-data">
          暂无事件数据
        </div>

        <!-- 有数据状态 -->
        <table v-else class="status-table">
          <thead>
            <tr>
              <th>时间</th>
              <th>事件ID</th>
              <th>事件类型</th>
              <th>事件码</th>
              <th>事件分类</th>
              <th>描述信息</th>
              <th>处理方案</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(event, index) in events" :key="index">
              <td>{{ formatTime(event.time) }}</td>
              <td>{{ event.eventId }}</td>
              <td>
                <div class="tag-cell">
                  <span :class="['status-tag', event.eventType.toLowerCase()]">
                    {{ event.eventType }}
                  </span>
                </div>
              </td>
              <td>{{ event.eventCode }}</td>
              <td>{{ event.eventCategory }}</td>
              <td>{{ event.description }}</td>
              <td>{{ event.solution }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import api from '../api/api'
import FlowDiagramNew from './FlowDiagramNew.vue'
import flvjs from 'flv.js'

// 模拟事件数据
const events = ref([])
const eventsLoading = ref(false)
let refreshInterval = null

// 视频播放器引用和状态管理
const camera1Video = ref(null)
const camera2Video = ref(null)
const cameraPlayers = {
  camera1: null,
  camera2: null
}

// 相机状态
const cameraStatus = ref({
  camera1: {
    playing: false,
    loading: false,
    error: false
  },
  camera2: {
    playing: false,
    loading: false,
    error: false
  }
})

// 相机流地址
// const cameraUrls = {
// 	camera1: "http://192.168.8.191:8083/live/galaxea.flv",
// 	camera2: "http://192.168.8.191:8083/live/leju.flv"
// };

const props = defineProps({
  itemData: {
    // 添加 prop 接收完整的 item 数据
    type: Object,
    default: () => ({})
  }
})
// 判断是哪个服务器取值
const isGalaxea = ref(false)
const baseURL = ref('http://192.168.8.191:8899/framework/v1')
// 根据itemData.spec.desc.docs获取相机流地址
const getCameraUrl = (itemData) => {
  console.log('itemData:', itemData)
  let cameraUrl = {}
  if (itemData?.spec?.desc?.docs === '星海图&乐聚的检测和抓取') {
    cameraUrl = {
      camera1: 'http://192.168.8.191:8083/live/galaxea.flv',
      camera2: 'http://192.168.8.191:8083/live/leju_1.flv'
    }
  } else {
    cameraUrl = {
      camera1: 'http://192.168.8.191:8083/live/leju_2.flv',
      camera2: 'http://192.168.8.191:8083/live/leju_3.flv'
    }
  }
  return cameraUrl
}
// 格式化时间函数
const formatTime = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString()
}



// 获取任务事件数据
const fetchEvents = async (isRefresh = false) => {
  // 检查itemData是否存在
  if (!props.itemData || !props.itemData.name || !props.itemData.namespace) {
    console.warn('无法获取任务事件：缺少任务信息', props.itemData)
    return
  }

  // 只在初始加载时显示加载状态，刷新时不显示
  if (!isRefresh) {
    eventsLoading.value = true
  }

  try {
    // 构建API请求参数
    const params = {
      Name: props.itemData.name,
      Namespace: props.itemData.namespace
    }

    console.log('获取任务事件数据，参数:', params)

    // 调用API获取任务事件数据
    const response = await api.getTaskEventsData({ params }, baseURL.value)
    console.log('获取任务事件响应:', response.data)

    // 将API返回的数据赋值给events
    if (response.data && response.data.items.length > 0) {
      events.value = response.data.items.map((event) => {return {
        time: event.EventTime,
        eventId: event.uid,
        eventType: event.kind,
        eventCode: event.eventCode || event.code || '-',
        eventCategory: event.eventCategory || event.category || '系统事件',
        description: event.Message,
        solution: event.solution || event.suggestion || '-'
      }})
    } else {
      console.warn('API返回的数据格式不正确:', response.data)
      events.value = []
    }
  } catch (error) {
    console.error('获取任务事件数据失败:', error)
    // 清空事件列表或保留现有事件
    if (!isRefresh) {
      events.value = []
    }
  } finally {
    // 无论成功失败都结束加载状态
    if (!isRefresh) {
      eventsLoading.value = false
    }
  }
}

// 控制相机播放/停止
const controlCamera = (camera, action) => {
  // 检查flv.js是否支持
  if (!flvjs.isSupported()) {
    console.error('您的浏览器不支持flv.js，无法播放视频流')
    cameraStatus.value[camera].error = true
    return
  }

  try {
    if (action === 'play') {
      // 设置加载状态
      cameraStatus.value[camera].loading = true
      cameraStatus.value[camera].error = false

      // 销毁可能存在的播放器实例
      destroyPlayer(camera)

      // 获取视频元素
      const videoElement =
        camera === 'camera1' ? camera1Video.value : camera2Video.value
      if (!videoElement) {
        throw new Error(`找不到${camera}的视频元素`)
      }

      // 创建新的播放器
      let cameraUrls = getCameraUrl(props.itemData)
      cameraPlayers[camera] = flvjs.createPlayer({
        type: 'flv',
        url: cameraUrls[camera],
        isLive: true,
        hasAudio: false,
        hasVideo: true,
        cors: true
      })

      // 监听事件
      cameraPlayers[camera].on(flvjs.Events.ERROR, (errorType, errorDetail) => {
        console.error(`${camera} 播放错误:`, errorType, errorDetail)
        cameraStatus.value[camera].error = true
        cameraStatus.value[camera].loading = false
        cameraStatus.value[camera].playing = false
      })

      cameraPlayers[camera].on(flvjs.Events.LOADING_COMPLETE, () => {
        console.log(`${camera} 加载完成`)
        cameraStatus.value[camera].loading = false
      })

      cameraPlayers[camera].on(flvjs.Events.MEDIA_INFO, (mediaInfo) => {
        console.log(`${camera} 媒体信息:`, mediaInfo)
      })

      // 绑定视频元素并开始播放
      cameraPlayers[camera].attachMediaElement(videoElement)
      cameraPlayers[camera].load()

      // 添加播放成功事件处理
      videoElement.onplaying = () => {
        cameraStatus.value[camera].playing = true
        cameraStatus.value[camera].loading = false
        console.log(`${camera} 开始播放`)
      }

      // 尝试播放
      const playPromise = videoElement.play()
      if (playPromise !== undefined) {
        playPromise.catch((error) => {
          console.error(`${camera} 自动播放失败:`, error)
          // 某些浏览器需要用户交互才能播放
        })
      }
    } else if (action === 'stop') {
      // 停止播放并销毁播放器
      destroyPlayer(camera)
      cameraStatus.value[camera].playing = false
    }
  } catch (error) {
    console.error(`${camera} 操作失败:`, error)
    cameraStatus.value[camera].error = true
    cameraStatus.value[camera].loading = false
  }
}

// 销毁播放器实例
const destroyPlayer = (camera) => {
  if (cameraPlayers[camera]) {
    try {
      cameraPlayers[camera].pause()
      cameraPlayers[camera].unload()
      cameraPlayers[camera].detachMediaElement()
      cameraPlayers[camera].destroy()
      cameraPlayers[camera] = null
    } catch (error) {
      console.error(`销毁${camera}播放器失败:`, error)
    }
  }
}
// 监听工作流数据变化
watch(
  () => props.itemData,
  (newVal) => {
    console.log('我的天啊:', newVal)
		if (newVal && newVal.spec && newVal.spec.desc && newVal.spec.desc.docs) {
      if (newVal.spec.desc.docs === '星海图&乐聚的检测和抓取') {
				isGalaxea.value = true
				baseURL.value = 'http://192.168.8.191:8899/framework/v1'
      } else {
        isGalaxea.value = false
				baseURL.value = 'http://192.168.1.199:8899/framework/v1'
      }
		}
		    if (newVal && newVal.name && newVal.namespace) {
      console.log('TaskDistribution组件接收到新的itemData:', newVal)
      // 当itemData变化时重新获取事件数据
      fetchEvents()
		}
  },
  {
		deep: true,
		immediate: true
  }
)
onMounted(() => {
  console.log('TaskDistribution组件挂载，接收的itemData:', props.itemData)
  fetchEvents() // 初始加载
  // 每10秒刷新一次事件数据，并标记为刷新操作
  refreshInterval = setInterval(() => fetchEvents(true), 1000)

  // 检查flv.js支持
  if (flvjs.isSupported()) {
    console.log('当前浏览器支持flv.js，可以播放监控视频')

    // 自动播放两个相机画面
    setTimeout(() => {
      controlCamera('camera1', 'play')
      controlCamera('camera2', 'play')
    }, 500) // 延迟500ms确保DOM已完全渲染
  } else {
    console.warn('当前浏览器不支持flv.js，无法播放监控视频')
  }
})

onUnmounted(() => {
  // 清除事件数据刷新定时器
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }

  // 销毁所有视频播放器
  destroyPlayer('camera1')
  destroyPlayer('camera2')
})
</script>


<style lang="scss" scoped>
.status-log-container {
  padding: 1.6vh;
  // background-color: #f0f2f5;
  // background: rgba(255, 255, 255, 0.1);
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  gap: 1.6vh;
  overflow: hidden;
  margin-right: 2vw;
  margin-left: 7vw;

  .top-section {
    display: flex;
    gap: 1.6vh;
    height: 44vh;
    width: 100%;
    max-height: 45vh;
    overflow: hidden;

    .flow-section {
      flex: 1;
      min-width: 0;
      overflow: hidden;
    }

    .camera-section {
      flex: 2;
      min-width: 0;
      overflow: hidden;
    }

    .flow-section,
    .camera-section {
      background: rgba(255, 255, 255, 0.1);
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      padding: 1.6vh;
      display: flex;
      flex-direction: column;

      h3 {
        margin: 0 0 1.6vh 0;
        font-size: 1.2vw;
        font-weight: 500;
        color: #fff;
      }
    }

    .flow-section {
      .flow-diagram {
        // flex: 1;
        display: flex;
        overflow: hidden;
        padding: 0;
        margin-top: 1vh;
        height: 100%;
      }
    }

    .camera-section {
      .camera-views {
        display: flex;
        gap: 1.6vh;
        flex: 1;
        overflow: hidden;
        height: calc(100% - 40px);

        .camera-view {
          flex: 1;
          min-width: 0;
          display: flex;
          flex-direction: column;
          border: 1px solid #e8e8e8;
          border-radius: 4px;
          overflow: hidden;
          max-height: 100%;

          .camera-header {
            padding: 0.8vh 1.2vh;
            background: #f5f5f5;
            font-size: 1.4vh;
            color: #fff;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .camera-controls {
              display: flex;
              gap: 0.8vh;

              button {
                padding: 0.2vh 0.8vh;
                background: #1890ff;
                border: none;
                border-radius: 2px;
                color: white;
                font-size: 1vw;
                cursor: pointer;

                &:hover {
                  background: #40a9ff;
                }
              }

              .camera-error {
                color: #f5222d;
                font-size: 1vw;
              }
            }
          }

          .camera-content {
            flex: 1;
            background-color: #000;
            position: relative;
            height: 0;
            padding-bottom: 56.25%;
            overflow: hidden;

            .camera-video {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              object-fit: contain;
            }

            .camera-placeholder {
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              bottom: 0;
              display: flex;
              align-items: center;
              justify-content: center;
              color: #999;
              font-size: 1.4vh;
              background-color: rgba(0, 0, 0, 0.6);
            }

            .camera-loading {
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              bottom: 0;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              color: #fff;
              font-size: 1.4vh;
              background-color: rgba(0, 0, 0, 0.6);

              .loading-spinner {
                border: 3px solid rgba(255, 255, 255, 0.3);
                border-top: 3px solid #fff;
                border-radius: 50%;
                width: 2.4vh;
                height: 2.4vh;
                animation: spin 1s linear infinite;
                margin-bottom: 0.8vh;
              }
            }
          }
        }
      }
    }
  }

  .status-table-section {
    flex: 1;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
    padding: 1.6vh 2.4vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    h3 {
      margin: 0 0 1vh 0;
      font-size: 1.2vw;
      font-weight: 500;
      color: #fff;
    }

    .table-container {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      border: 1px solid rgba(0, 0, 0, 0.1);
      border-radius: 4px;

      &::-webkit-scrollbar {
        width: 0.6vh;
        height: 0.6vh;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb:hover {
        background: #999;
      }

      .status-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        table-layout: fixed;

        th,
        td {
          padding: 1vh;
          text-align: center;
          font-size: 1.8vh;
          border-bottom: 1px solid #f0f0f0;
          vertical-align: middle;
          word-wrap: break-word;
          word-break: break-word;
        }

        th {
          background: #2e5fac;
          font-weight: 500;
          color: #fff;
          white-space: nowrap;
          position: sticky;
          top: 0;
          z-index: 1;
          padding-top: 2vh;
          padding-bottom: 2vh;
        }

        tbody tr {
          height: 6vh;
          transition: background-color 0.3s;

          &:nth-child(even) {
            // background-color: #fafafa;
          }

          &:hover {
            background-color: rgba($color: #2e5fac, $alpha: 0.5);
          }

          &:last-child td {
            border-bottom: none;
          }
        }

        td {
          color: #fff;
          line-height: 1.6;
          background-color: transparent !important;

          .tag-cell {
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1.2vh;
            height: 100%;
          }
        }

        th:first-child,
        td:first-child {
          padding-left: 4vh;
          width: 6%;
        }

        th:nth-child(2),
        td:nth-child(2) {
          padding-left: 5vh;

          width: 10%;
        }

        th:nth-child(3),
        td:nth-child(3) {
          width: 6vh;
          text-align: center;
        }

        th:nth-child(4),
        td:nth-child(4) {
          width: 10%;
          text-align: center;
        }

        th:nth-child(5),
        td:nth-child(5) {
          width: 12%;
        }

        th:nth-child(6),
        td:nth-child(6) {
          width: 15%;
        }

        th:nth-child(7),
        td:nth-child(7) {
          width: 13%;
          text-align: center;
        }

        .status-tag {
          width: 9vh;
          height: 2.4vh;
          border-radius: 1.2vh;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          font-size: 1.2vh;

          &.info {
            background-color: #e6f7ff;
            color: #1890ff;
            border: 1px solid #91d5ff;
          }

          &.warning {
            background-color: #fff7e6;
            color: #faad14;
            border: 1px solid #ffd591;
          }

          &.error {
            background-color: #fff1f0;
            color: #f5222d;
            border: 1px solid #ffa39e;
          }
        }
      }
    }
  }
}

.error-type {
  color: #ff4d4f;
}

.info-type {
  color: #1890ff;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 20vh;

  .loading-spinner {
    border: 3px solid #f3f3f3;
    border-top: 3px solid #1890ff;
    border-radius: 50%;
    width: 3vh;
    height: 3vh;
    animation: spin 1s linear infinite;
    margin-bottom: 1.6vh;
  }

  .loading-text {
    color: #fff;
    font-size: 1.2vw;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 空数据提示样式 */
.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 20vh;
  color: #fff;
  font-size: 1.2vw;
  font-style: italic;
}
</style>